export async function useFetchSSE(resource, requestOptions, responseOptions) {
  const { onMessage, onError, onComplete } = responseOptions;
  const resPromise = fetch(resource, requestOptions);
  resPromise
    .then(async (response) => {
      if (!response.ok) {
        const { status } = response;
        throw new Error(`HTTP error! status: ${status}`);
      }

      const reader = response.body.getReader();
      const decoder = new TextDecoder("utf-8");
      let buffer = "";
      while (true) {
        const { done, value } = await reader.read();
        if (done) {
          onComplete();
          return Promise.resolve();
        }

        buffer += decoder.decode(value, { stream: true });
        const lines = buffer.split("\n");
        buffer = lines.pop();
        for (const line of lines) {
          // console.log(line);
          if (line.trim() === "") continue;
          try {
            const chunk = JSON.parse(line);
            onMessage(chunk);
            if (chunk.done) {
              break;
            }
          } catch (error) {
            onError(error);
          }
        }
      }
    })
    .catch((error) => {
      onError(error);
    });
}
